package zhoug.zui;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;

import zhoug.common.adapters.recycler2.BaseRecyclerViewAdapter;
import zhoug.common.adapters.recycler2.BaseViewHolder;
import zhoug.common.anim.ZAnimations;
import zhoug.common.content.FileType;
import zhoug.common.imageloader.wrap.GlideHelper;
import zhoug.common.utils.IntentUtils;
import zhoug.common.utils.StringUtils;
import zhoug.common.utils.ToastUtils;
import zhoug.common.utils.file.IFile;
import zhoug.zui.dialog.list.ZUIStringListDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 文件预览列表
 *
 * @Author: zhoug
 * @Date: 2024-07-17
 * @Description:
 */
public class ZUIFilePreview extends FrameLayout {
    private static final String TAG = ">>>FilePreviewListView";
    protected RecyclerView mRecyclerView;
    protected FileListAdapter mFileListAdapter;
    private @DrawableRes int loadErrorImageRes;//设置加载失败占位图
    private @DrawableRes int placeholderImageRes;//默认占位图
    private @DrawableRes int fallbackImageRes;//没有图片暂未图

    private @DrawableRes int fileTypeAudioThumbnail;
    private @DrawableRes int fileTypeDocThumbnail;
    private @DrawableRes int fileTypeExcelThumbnail;
    private @DrawableRes int fileTypePdfThumbnail;
    private @DrawableRes int fileTypeTxtThumbnail;
    private @DrawableRes int fileTypeUnknownThumbnail;


    private List<IFile> files = new ArrayList<>();
    private int spanCount = 4;
    private boolean deleteEnable = false;//是否可以删除
    private int imageCorners = 0;
    /**
     * 是否支持水平滚动
     */
    private boolean canScrollHorizontally;
    /**
     * 是否支持垂直滚动
     */
    private boolean canScrollVertically;
    private OnDeleteListener onDeleteListener;
    private OnPreviewFileClickListener onPreviewFileClickListener;

    public ZUIFilePreview(@NonNull Context context) {
        this(context, null);
    }

    public ZUIFilePreview(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, R.attr.ZUIFilePreview_theme);
    }

    public ZUIFilePreview(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);

    }

    private void init(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ZUIFilePreview, defStyleAttr, R.style.ZUIFilePreview_def);
        loadErrorImageRes = a.getResourceId(R.styleable.ZUIFilePreview_zui_loadErrorImageRes,R.drawable.zui_placeholder_img);
        placeholderImageRes = a.getResourceId(R.styleable.ZUIFilePreview_zui_placeholderImageRes,R.drawable.zui_placeholder_img);
        fallbackImageRes = a.getResourceId(R.styleable.ZUIFilePreview_zui_fallbackImageRes,R.drawable.zui_placeholder_img);
        fileTypeAudioThumbnail = a.getResourceId(R.styleable.ZUIFilePreview_zui_fileTypeAudioThumbnail,0);
        fileTypeDocThumbnail = a.getResourceId(R.styleable.ZUIFilePreview_zui_fileTypeDocThumbnail,0);
        fileTypeExcelThumbnail = a.getResourceId(R.styleable.ZUIFilePreview_zui_fileTypeExcelThumbnail,0);
        fileTypePdfThumbnail = a.getResourceId(R.styleable.ZUIFilePreview_zui_fileTypePdfThumbnail,0);
        fileTypeTxtThumbnail = a.getResourceId(R.styleable.ZUIFilePreview_zui_fileTypeTxtThumbnail,0);
        fileTypeUnknownThumbnail = a.getResourceId(R.styleable.ZUIFilePreview_zui_fileTypeUnknownThumbnail,0);
        spanCount = a.getInt(R.styleable.ZUIFilePreview_zui_spanCount,4);
        deleteEnable = a.getBoolean(R.styleable.ZUIFilePreview_zui_deleteEnable,false);
        imageCorners = a.getDimensionPixelOffset(R.styleable.ZUIFilePreview_zui_imageCorners,0);
        canScrollHorizontally = a.getBoolean(R.styleable.ZUIFilePreview_zui_canScrollHorizontally,false);
        canScrollVertically = a.getBoolean(R.styleable.ZUIFilePreview_zui_canScrollVertically,false);
        String onPreviewFileClickListenerClass = a.getString(R.styleable.ZUIFilePreview_zui_OnPreviewFileClickListener);
        a.recycle();
        //创建点击预览接口
        OnPreviewFileClickListener onPreviewFileClickListener=null;
        if(onPreviewFileClickListenerClass!=null){
            try {
                Class<?> aClass = Class.forName(onPreviewFileClickListenerClass);
                Object object = aClass.newInstance();
                if(object instanceof OnPreviewFileClickListener ){
                    onPreviewFileClickListener= (OnPreviewFileClickListener) object;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
       setOnPreviewFileClickListener(onPreviewFileClickListener);

        mRecyclerView = new RecyclerView(context);
        mRecyclerView.setOverScrollMode(OVER_SCROLL_NEVER);
        mRecyclerView.setVerticalScrollBarEnabled(false);
        mRecyclerView.setHorizontalScrollBarEnabled(false);
        mRecyclerView.setId(View.generateViewId());
        LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        mFileListAdapter = new FileListAdapter();
        mFileListAdapter.setData(files);
        mFileListAdapter.setOnItemClickListener(onItemClickListener);
        mRecyclerView.setLayoutManager(new GridLayoutManager(context, spanCount) {
            @Override
            public boolean canScrollHorizontally() {
//                return super.canScrollHorizontally();
                return canScrollHorizontally;
            }

            @Override
            public boolean canScrollVertically() {
//                return super.canScrollVertically();
                return canScrollVertically;
            }
        });
        mRecyclerView.setAdapter(mFileListAdapter);
        addView(mRecyclerView, layoutParams);
    }


    /**
     * 图片单击事件
     */
    private BaseRecyclerViewAdapter.OnItemClickListener<IFile> onItemClickListener = new BaseRecyclerViewAdapter.OnItemClickListener<IFile>() {
        @Override
        public void onItemClick(BaseRecyclerViewAdapter<IFile> adapter, View view, int position) {
            IFile comFile = mFileListAdapter.getItemData(position);
            if (deleteEnable) {
                ZUIStringListDialog dialog = new ZUIStringListDialog(getContext());
                dialog.setCanceledOnTouchOutside(true);
                dialog.setAttributes(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
                dialog.setFullWidth(true);
                dialog.setTitle(null);
                dialog.setWindowAnimations(ZAnimations.ANIM_DOWN);
                dialog.setData(Arrays.asList("查看", "删除"));
                dialog.setOnItemClickListener(pos -> {
                    dialog.cancel();
                    if (pos == 0) {
                        //查看
//                        toast("查看");
                        if (onPreviewFileClickListener != null) {
                            onPreviewFileClickListener.onPreviewFileClick(self(), files, position);
                        }
                    } else if (pos == 1) {
                        //删除
                        files.remove(comFile);
                        mFileListAdapter.notifyDataSetChanged();
                        if (onDeleteListener != null) {
                            onDeleteListener.onDeleteFile(self(), position, comFile);
                        }
//                        toast("删除");
                    }
                });
                dialog.show();
            } else {
                //查看
//                toast("查看");
                if (onPreviewFileClickListener != null) {
                    onPreviewFileClickListener.onPreviewFileClick(self(), files, position);
                }
            }


        }
    };



    protected class FileListAdapter extends BaseRecyclerViewAdapter<IFile> {

        @Override
        protected int getLayoutId(int viewType) {
            return R.layout.zui_file_preview_item;
        }

        @Override
        protected void onBindData(BaseViewHolder holder, IFile data, int position, int viewType) {
            if (data != null) {
                ImageView fileImageView = holder.getView(R.id.file_preview_file);
                ImageView fileTypeImageView = holder.getView(R.id.file_preview_file_type);
//                Logger.d(TAG, "onBindData: data=" + data);
                int fileType = data.getFileType();
                //视频时显示播放图标
                if (fileType == FileType.VIDEO) {
                    fileTypeImageView.setVisibility(VISIBLE);
                } else {
                    fileTypeImageView.setVisibility(GONE);
                }
                if (fileType == FileType.IMAGE || fileType == FileType.VIDEO) {
                    //图片和视频加载缩率图
                    loadImage(fileImageView, data.getRealUrl());

                } else {
                    int fileTypeIcon = getFileTypeIcon(fileType);
                    loadImage(fileImageView, fileTypeIcon);

                }

            }

        }


    }

    public void setLoadErrorImageRes(int loadErrorImageRes) {
        this.loadErrorImageRes = loadErrorImageRes;
    }

    public void setFallbackImageRes(int fallbackImageRes) {
        this.fallbackImageRes = fallbackImageRes;
    }

    public void setPlaceholderImageRes(int placeholderImageRes) {
        this.placeholderImageRes = placeholderImageRes;
    }

    public void setFileTypeAudioThumbnail(int fileTypeAudioThumbnail) {
        this.fileTypeAudioThumbnail = fileTypeAudioThumbnail;
    }

    public void setFileTypeDocThumbnail(int fileTypeDocThumbnail) {
        this.fileTypeDocThumbnail = fileTypeDocThumbnail;
    }

    public void setFileTypeExcelThumbnail(int fileTypeExcelThumbnail) {
        this.fileTypeExcelThumbnail = fileTypeExcelThumbnail;
    }

    public void setFileTypePdfThumbnail(int fileTypePdfThumbnail) {
        this.fileTypePdfThumbnail = fileTypePdfThumbnail;
    }

    public void setFileTypeTxtThumbnail(int fileTypeTxtThumbnail) {
        this.fileTypeTxtThumbnail = fileTypeTxtThumbnail;
    }

    public void setFileTypeUnknownThumbnail(int fileTypeUnknownThumbnail) {
        this.fileTypeUnknownThumbnail = fileTypeUnknownThumbnail;
    }

    public void setSpanCount(int spanCount) {
        if (this.spanCount != spanCount && spanCount > 0) {
            this.spanCount = spanCount;
            if (mRecyclerView != null) {
                RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
                if (layoutManager instanceof GridLayoutManager gridLayoutManager) {
                    gridLayoutManager.setSpanCount(spanCount);
                }
            }
        }
    }

    public void setCanScrollHorizontally(boolean canScrollHorizontally) {
        this.canScrollHorizontally = canScrollHorizontally;
    }

    public void setCanScrollVertically(boolean canScrollVertically) {
        this.canScrollVertically = canScrollVertically;
    }

    public void setImageCorners(int imageCorners) {
        this.imageCorners = imageCorners;
    }

    public boolean isDeleteEnable() {
        return deleteEnable;
    }

    public void setDeleteEnable(boolean deleteEnable) {
        this.deleteEnable = deleteEnable;
    }


    public void notifyDataSetChanged() {
        if (mFileListAdapter != null) {
            mFileListAdapter.notifyDataSetChanged();
        }
    }

    public void addFile(IFile file) {
        if (file != null) {
            this.files.add(file);
            notifyDataSetChanged();
        }
    }

    public void addAllFile(List<? extends IFile> files) {
        if (files != null && !files.isEmpty()) {
            this.files.addAll(files);
            notifyDataSetChanged();
        }
    }

    public void setFiles(List<? extends IFile> files) {
        this.files.clear();
        if (files != null && !files.isEmpty()) {
            this.files.addAll(files);
        }
        notifyDataSetChanged();
    }

    public void setFile(IFile file) {
        this.files.clear();
        if (file != null) {
            this.files.add(file);
        }
        notifyDataSetChanged();
    }

    public void clear() {
        if (!files.isEmpty()) {
            files.clear();
            notifyDataSetChanged();
        }
    }

    public List<IFile> getFiles() {
        return files;
    }

    public IFile getFile() {
        return files.isEmpty() ? null : files.get(0);
    }


    public RecyclerView getRecyclerView() {
        return mRecyclerView;
    }


    protected void loadImage(ImageView fileImageView, Object imageUrl) {
        GlideHelper.with(getContext())
                //设置默认图,可以再次调用相应的方法修改或取消
                .placeholder(placeholderImageRes)//默认占位图
                .fallback(fallbackImageRes)//没有图片
                .error(loadErrorImageRes)//错误图
                .load(imageUrl)
                .setRoundedCorners(imageCorners)
                .into(fileImageView);

    }

    /**
     * 获取文件类型图标
     *
     * @param fileType
     * @return
     */
    protected int getFileTypeIcon(int fileType) {
        if (fileType == FileType.AUDIO) {
            return fileTypeAudioThumbnail != 0 ? fileTypeAudioThumbnail : R.drawable.zui_file_type_audio_thumbnail;
        } else if (fileType == FileType.WORD) {
            return fileTypeDocThumbnail != 0 ? fileTypeDocThumbnail : R.drawable.zui_file_type_doc_thumbnail;
        } else if (fileType == FileType.EXCEL) {
            return fileTypeExcelThumbnail != 0 ? fileTypeExcelThumbnail : R.drawable.zui_file_type_excel_thumbnail;
        } else if (fileType == FileType.PDF) {
            return fileTypePdfThumbnail != 0 ? fileTypePdfThumbnail : R.drawable.zui_file_type_pdf_thumbnail;
        } else if (fileType == FileType.TXT) {
            return fileTypeTxtThumbnail != 0 ? fileTypeTxtThumbnail : R.drawable.zui_file_type_txt_thumbnail;
        }
        return fileTypeUnknownThumbnail != 0 ? fileTypeUnknownThumbnail : R.drawable.zui_file_type_unknown_thumbnail;
    }


    private ZUIFilePreview self() {
        return this;
    }

    public OnDeleteListener getOnDeleteListener() {
        return onDeleteListener;
    }

    public void setOnDeleteListener(OnDeleteListener onDeleteListener) {
        this.onDeleteListener = onDeleteListener;
    }


    public void setOnPreviewFileClickListener(OnPreviewFileClickListener onPreviewFileClickListener) {
        if(onPreviewFileClickListener!=null){
            this.onPreviewFileClickListener = onPreviewFileClickListener;
        }else{
            this.onPreviewFileClickListener = new DefOnPreviewFileClickListener();
        }
    }

    /**
     * 删除图片监听
     */
    public interface OnDeleteListener {
        /**
         * @param view
         * @param position
         * @param file
         */
        void onDeleteFile(ZUIFilePreview view, int position, IFile file);
    }

    /**
     * 预览图片点击监听
     */
    public interface OnPreviewFileClickListener {
        void onPreviewFileClick(ZUIFilePreview view, List<IFile> data, int position);
    }


    public static class DefOnPreviewFileClickListener implements OnPreviewFileClickListener{

        @Override
        public void onPreviewFileClick(ZUIFilePreview view, List<IFile> data, int position) {
            Context context = view.getContext();
            IFile iFile = data.get(position);
            String realUrl = iFile.getRealUrl();
            if(StringUtils.isNullOrEmpty(realUrl)){
                ToastUtils.toastLong("文件路径为空");
                return;
            }
            String mimeType = FileType.getMimeType(iFile.getFileType());
            Intent readFileIntent = IntentUtils.getReadFileIntent(context, realUrl, mimeType);
            context.startActivity(readFileIntent);
        }
    }

}
